#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: kubesphere.py.py 
@version:
@time: 2021/06/23 
"""
import time
from pprint import pprint
from requests import session
import requests.utils
from requests import request


class Kubesphere():
    headers = {}
    server = "192.168.1.185:31405"
    web_server = 'devops.tapdata.net'
    login_data = {"grant_type": "password", "username": "admin", "password": "Gotapd8!"}

    def kube_request(self, method, url, **kwargs):
        while True:
            response = request(method=method, url=url, headers=self.headers, **kwargs)
            if 'message' in response.json():
                if "Unauthorized" not in response.json()['message']:
                    return response
                else:
                    continue
            else:
                return response

    def __init__(self):
        self.get_token()

    def get_token(self):
        method = "POST"
        url = f"http://{self.server}/oauth/token"

        res = self.kube_request(method=method,
                                url=url,
                                data=self.login_data)
        self.headers["Authorization"] = "Bearer " + res.json()["access_token"]

    def work_load(self, worker_name):
        return f"http://{self.web_server}/clusters/host/projects/dev/deployments/{worker_name}/resource-status"

    def get_node_info(self):
        # 获取集群worker信息
        method = "GET"
        url = f"http://{self.server}/kapis/resources.kubesphere.io/v1alpha3/nodes"
        res = self.kube_request(method=method, url=url)
        return res.json()

    def search_pod(self, worker_name):
        # 根据worker名称搜索pod信息
        method = "GET"
        url = f"http://{self.server}/kapis/clusters/host/resources.kubesphere.io/v1alpha3/pods?name={worker_name}&sortBy=startTime&limit=10"
        res = self.kube_request(method=method, url=url)
        return res.json()

    def get_worker_setting_yml(self, name="tapdaas-test-tapdaas"):
        # 获取worker 配置yaml
        method = "GET"
        url = f"http://{self.server}/apis/clusters/host/apps/v1/namespaces/dev/deployments/{name}"
        res = self.kube_request(method=method, url=url)
        return res.json()["spec"]["template"]["spec"]["containers"][0]

    def get_pod_info(self, worker_name):
        pod_info = self.search_pod(worker_name=worker_name)["items"][0]
        current_pod_name = pod_info["metadata"]["name"]
        container_ready = pod_info["status"]["containerStatuses"][0]
        container_status = pod_info["status"]["phase"]
        current_pod_can_use = container_ready["ready"]
        current_pod_image = container_ready["image"]
        current_pod_status = container_status
        # current_pod_docker_id = container_status["containerID"]
        return {"worker_name": worker_name, "podname": current_pod_name, "ready": current_pod_can_use,
                "status": current_pod_status, "image": current_pod_image}

    # def get_server_info(self):
    #     method = "GET"
    #     url = f"http://{self.server}/api/clusters/host/v1/namespaces/dev/pods/v1-24-tapdaas-tapdaas-7b55c86c6c-hvmv8"
    #     res = self.kube_request(method, url)
    #     print(res.json())

    def update_template(self, worker_name, update_image, db_info=None):
        """
        更新podtemplate
        :return:
        """
        ...
        method = "PUT"
        url = f'http://{self.server}/apis/clusters/host/apps/v1/namespaces/dev/deployments/{worker_name}'
        put_body = self.get_worker_template(worker_name).json()
        if update_image:
            put_body['spec']['template']['spec']['containers'][0]['image'] = update_image
        if db_info:
            put_body['spec']['template']['spec']['containers'][0]['env'][0]["value"] = db_info[
                                                                                           "ip_port_db"] + "?authSource=admin"
            put_body['spec']['template']['spec']['containers'][0]['env'][2]["value"] = db_info['username']
            put_body['spec']['template']['spec']['containers'][0]['env'][1]["value"] = db_info['password']
        result = self.kube_request(method, url, json=put_body)
        return result.json()

    def get_worker_template(self, worker_name):
        # 获取当前template
        method = "GET"
        url = f'http://{self.server}/apis/clusters/host/apps/v1/namespaces/dev/deployments/{worker_name}'
        result = self.kube_request(method, url)
        return result
        # mongodb_uri = result.json()['spec']['template']['spec']['containers'][0]['env'][0]["value"]
        # images = result.json()['spec']['template']['spec']['containers'][0]['image']
        # return {"mongodb_uri": mongodb_uri, "images": images}

    def get_worker_outside_port(self, work_name):
        method = 'GET'
        url = f'http://{self.server}/api/clusters/host/v1/namespaces/dev/services/{work_name}'
        result = self.kube_request(method, url).json()
        ports = result['spec']['ports']
        for k in ports:
            if k['port'] == 3030:
                return k['nodePort']

    def get_worker_by_port(self, port):
        method = 'GET'
        url = f'http://{self.server}/api/clusters/host/v1/namespaces/dev/services'
        result = self.kube_request(method, url).json()
        for i in result['items']:
            tmp = i['metadata']['managedFields'][0]['fieldsV1']['f:spec']['f:ports']
            if 'k:{"port":3030,"protocol":"TCP"}' in tmp:
                tmp2 = i['spec']['ports']
                for j in tmp2:
                    if str(j['nodePort']) == port:
                        return i['metadata']['name']
        return None


class KubesphereTest():
    headers = {"Content-Type": "application/json"}
    session = None
    server = 'http://192.168.3.72:30880'

    def __init__(self):
        if self.session is None:
            self.session = session()
        self.login()

    def kube_request(self, method, url, **kwargs):
        return self.session.request(method=method, url=url, headers=self.headers, **kwargs)

    def login(self):
        url = f"{self.server}/login"
        method = "POST"
        data = {
            "username": "admin",
            "encrypt": "MTExMTAwMDExMDAxMTAxMDAwMDAxMDEx@^SMJfdUoiVTSI1ddNgS`QcK7"
        }
        self.kube_request(method, url, json=data)
        set_cookie = requests.utils.dict_from_cookiejar(self.session.cookies)
        set_cookie = [f"{k}={v}" for k, v in set_cookie.items()]
        s = ''
        for i in set_cookie:
            i = i + "; "
            s += i
        set_cookie = {"Cookie": s}
        print(set_cookie)
        self.headers = set_cookie

    def search_pod(self, worker_name):
        # 根据worker名称搜索pod信息
        method = "GET"
        url = f"{self.server}/kapis/resources.kubesphere.io/v1alpha3/pods?name={worker_name}&sortBy=startTime&limit=10"
        res = self.kube_request(method=method, url=url)
        return res.json()

    def get_pod_info(self, worker_name):
        pod_info = self.search_pod(worker_name=worker_name)["items"][0]
        current_pod_name = pod_info["metadata"]["name"]
        container_ready = pod_info["status"]["containerStatuses"][0]
        container_status = pod_info["status"]["phase"]
        current_pod_can_use = container_ready["ready"]
        current_pod_image = container_ready["image"]
        current_pod_status = container_status
        # current_pod_docker_id = container_status["containerID"]
        return {"worker_name": worker_name, "podname": current_pod_name, "ready": current_pod_can_use,
                "status": current_pod_status, "image": current_pod_image}

    def get_worker_template(self, worker_name):
        # 获取当前template
        method = "GET"
        url = f'{self.server}/apis/apps/v1/namespaces/test/deployments/{worker_name}'
        result = self.kube_request(method, url)
        return result

    def update_template(self, worker_name, update_image, db_info=None):
        """
        更新podtemplate
        :return:
        """
        ...
        method = "PUT"
        url = f'{self.server}/apis/apps/v1/namespaces/test/deployments/{worker_name}'
        put_body = self.get_worker_template(worker_name).json()
        put_body['spec']['template']['spec']['containers'][0]['image'] = update_image
        if db_info:
            put_body['spec']['template']['spec']['containers'][0]['env'][0]["value"] = db_info[
                                                                                           "ip_port_db"] + "?authSource=admin"
            put_body['spec']['template']['spec']['containers'][0]['env'][2]["value"] = db_info['username']
            put_body['spec']['template']['spec']['containers'][0]['env'][1]["value"] = db_info['password']
        result = self.kube_request(method, url, json=put_body)
        return result.json()


if __name__ == '__main__':
    k = Kubesphere()
    res = k.get_worker_by_port('31603')
    # harbor.devops.tapdata.net:30002/tapdaas/v1.25:v1.24.0-948-g015c83420
    # res = k.update_template('tapdaas-jsdk-tapdaas',
    #                         'harbor.devops.tapdata.net:30002/tapdaas/v1.25:v1.24.0-949-g68229e111',
    #                         {"ip_port_db": "47.115.163.10:27017/tapdaas-jsdk", "username": "", "password": ""})
    # print(res)

    # t = KubesphereTest()
    # res = t.get_pod_info('apdaas-deployment-01')
    # print(res)
    # res = t.get_worker_template('tapdaas-deployment-01')
    # print(res.json())
    # res = t.update_template('tapdaas-deployment-01',
    #                         'harbor.devops.tapdata.net:30002/tapdaas/v1.21:1.21.14-10-gf2a3da549',
    #                         {"ip_port_db": "192.168.1.181:32560/tapdaas-deployment-01", "username": "root", "password": "Gotapd8!"})
    # res = t.update_template('tapdaas-deployment-02',
    #                         'harbor.devops.tapdata.net:30002/tapdaas/v1.21:1.21.14-10-gf2a3da549',
    #                         {"ip_port_db": "192.168.1.181:32560/tapdaas-deployment-02", "username": "root", "password": "Gotapd8!"})
    # res = t.update_template('tapdaas-deployment-03',
    #                         'harbor.devops.tapdata.net:30002/tapdaas/v1.21:1.21.14-10-gf2a3da549',
    #                         {"ip_port_db": "192.168.1.181:32560/tapdaas-deployment-03", "username": "root", "password": "Gotapd8!"})
